<?php

    require('../globals.inc');
    $mikron->Page->StartBody();
    require_once('menu.inc');
    
        if(isset($_REQUEST['ok']))
        {
            switch($_REQUEST['ok'])
            {
                case 'export':
                    $message = 'Экспорт выполнен успешно за '.$_GET['timeleft'].' сек.';
                    break;
                case "import":
                    $message = "Импорт выполнен успешно.";
                    break;
                default:
                    $message = "Операция выполнена успешно.";
                    break;
            }
            echo "<br />", $message, "<br />";
        }

        function getSQL($sql, $tablename)
        {
            $columns = '';
            $result = mysql_query($sql);
            if(mysql_num_rows($result) > 0)
            {
                
                // $columns .= "DELETE FROM $tablename;\r\n";
                echo "DELETE FROM $tablename;\r\n";
                while($row = mysql_fetch_assoc($result))
                {
                    // $columns .= 'INSERT INTO '.$tablename;
                    echo 'INSERT INTO '.$tablename;
                    $cols = Array();
                    $values = Array();
                    foreach($row as $key => $value)
                    {
                        if(is_null($value))
                        {
                            $cols[] = "`$key`";
                            $values[] = 'NULL';
                        }
                        else
                        {
                            $value2 = quote_smart($value);
                            $cols[] = "`$key`";
                            $values[] = $value2;
                        }
                    }
                    // $columns .= '('.implode(',', $cols).') VALUES('.implode(',', $values).')'.";\r\n";
                    echo '('.implode(',', $cols).') VALUES('.implode(',', $values).')'.";\r\n";
                }
            }
            // return $columns;
        }

        function getSQLEx($sql, $tablename, $inserts_per_query = 40)
        {
            $buffer = null;
            $columns = '';
            $result = mysql_query($sql);
            if(mysql_num_rows($result) < 1)
            {
                return;
            }
            $new_line = "\r\n";
            /**
            * Define columns
            */
            $columns = Array();
            while ($field = mysql_fetch_field($result))
            {
                $columns[] = '`'.$field->name.'`';
            }
            $columns = '('.implode(',', $columns).')';
            $insert = $new_line.'INSERT INTO '.$tablename.' '.$columns.' VALUES '.$new_line;
            echo 'DELETE FROM '.$tablename.';';
            $inserts = 0;
            $count = mysql_num_rows($result);
            while($row = mysql_fetch_assoc($result))
            {
                $full_line = ($inserts % $inserts_per_query) == 0;
                if($full_line)
                {
                    echo $insert;
                }
                $values2 = array_values($row);
                $values = Array();
                foreach($values2 as $value)
                {
                    if(is_null($value))
                    {
                        $values[] = 'NULL';
                    }
                    else
                    {
                        if(is_numeric($value))
                        {
                            $values[] = $value;
                        }
                        else
                        {
                            $values[] = quote_smart($value);
                        }
                    }
                }
                echo '('.implode(',', $values).')';
                $inserts++;
                if($inserts < $count)
                {
                    if(($inserts % $inserts_per_query) > 0)
                    {
                        echo ','.$new_line;
                    }
                    else
                    {
                        echo ';';
                    }
                }
            }
            if($count > 0)
            {
                echo ';';
            }
            mysql_free_result($result);
        }

        function getXML($sql, $tablename)
        {
            $columns = '';
            $result = mysql_query($sql);
            if(mysql_num_rows($result)>0)
            {
                $columns .= "<$tablename>";
                while($row = mysql_fetch_assoc($result))
                {
                    $columns .= '<record>';
                    foreach($row as $key => $value)
                    {
                        if(is_null($value) || ($value==""))
                        {
                            $columns .= "<$key />"; 
                        }
                        else
                        {
                            $pos0 = strpos($value, '<');
                            if($pos0 === false)
                            {
                                $pos0 = strpos($value, '&');
                            }
                            if($pos0 === false)
                            {
                                $columns .= "<$key>$value</$key>";
                            }
                            else
                            {
                                $value = htmlspecialchars($value);
                                $columns .= "<$key>$value</$key>";
                            }
                        }
                    }
                    $columns .= '</record>';
                }
                $columns .= "</$tablename>";
            }
            return $columns;
        }

        function make_export()
        {
            global $mikron;
            $xml = '';
            $sql = '';
            // $result = mysql_query('SELECT * FROM ENTITIES');
            $includelog = false;
            $export = Array();
            if(isset($_POST['export']))
            {
                $export = $_POST['export'];
            }
            $export_entity_names = Array();
            $export_selected_entity = false;
            if(isset($_POST['entitiy_names_export_only']))
            {
                $export_entity_names = $_POST['entitiy_names_export_only'];
                $export_selected_entity = true;
            }
            else
            {
                $export_entity_names = $mikron->EntityManager->Items();
            }
            $includelog = array_key_exists('includelog', $export);
            $includerecycle = array_key_exists('includerecycle', $export);
            $wherecondition = $includerecycle?'':'WHERE `mikron_state`=0';
            ob_start();
            //while($row = mysql_fetch_object($result))
            foreach($export_entity_names as $entityname)
            {
                if(!(($entityname == 'T_LOGRECORD') && (!$includelog)))
                {
                    // $xml .= getXML("SELECT * FROM $entityname $wherecondition", $entityname)."\r\n\r\n";
                    // $sql .= getSQL("SELECT * FROM $entityname $wherecondition", $entityname)."\r\n";
                    // getSQL('SELECT * FROM '.$entityname.' '.$wherecondition, $entityname);
                    getSQLEx('SELECT * FROM '.$entityname.' '.$wherecondition, $entityname);
                    echo "\r\n";
                }
            }
            $sql = ob_get_clean();
            ob_end_clean();

            $xml = '<'.'?xml version="1.0" encoding="utf-8"?'.">\r\n\r\n
            <tables>".trim($xml).'</tables>';
            $dt = date($mikron->Constants->DateTimeFormatForFileName);
            $site = constant('SITE_NAME');
            $file_name_ext = $export_selected_entity ? '_selected' : null;
            $about_selected = $export_selected_entity ? implode(', ', $export_entity_names): null;
            $comment = sprintf("/* %s\r\n%s */\r\n\r\n", date($mikron->Constants->DateTimeFormat), $about_selected);
            $exp_fir = constant('CURRENTSITE_DIR').'/private/backups';
            if(!file_exists($exp_fir))
            {
                mkdir($exp_fir, 0777, true);
            }
            $export_sql_filename2 = $exp_fir.'/exp_'.$site.'_'.$dt.$file_name_ext.'.sql';
            file_put_contents($export_sql_filename2, $comment."SET NAMES utf8;\r\n\r\n".$sql, LOCK_EX) or CriticalError('Ошибка sql-экспорта данных.');
        }
        
        if(isset($_REQUEST['makeexport']))
        {
            $timer = new MikronTimer();
            make_export();
            $time_left = $timer->elapsed();
            ob_clean();
            header('Location: '.$_SERVER['SCRIPT_NAME'].'?ok=export&timeleft='.$time_left);
            exit;
        }
        elseif(isset($_GET['doimport']))
        {
            $import_filename = $_GET['doimport'];
            if(!file_exists($import_filename))
            {
                throw new Exception('Import file not found.');
            }
            $result = mysql_query('SELECT * FROM ENTITIES');
            $entitytables = Array();
            while($row = mysql_fetch_object($result))
            {
                $entitytables[] = $row->name;
            }
            $xml = file_get_contents($import_filename);
            $dom = new DOMDocument();
            $dom->load($import_filename);
            $datatag = $dom->getElementsByTagName('tables');
            if($datatag->length == 0)
            {
                CriticalError('Испорченный бэкап.');
            }
            $tsql = Array();
            foreach($entitytables as $entityname)
            {
                $table = $dom->getElementsByTagName($entityname);
                $tsql[] = 'DELETE FROM '.$entityname;
                if($table->length > 0)
                {
                    foreach($table as $t)
                    {
                        $records = $t->getElementsByTagName('record');
                        if($records->length > 0)
                        {
                            $e = new $entityname();
                            foreach($records as $record)
                            {
                                $fieldscollection = Array();
                                $fields = null;
                                $fields = $record->childNodes;
                                $fieldsnames = Array();
                                $values = Array();
                                foreach($fields as $field)
                                {
                                    $fieldname = $field->nodeName;
                                    // Определение это child-attribute или нет
                                    $childattribute = null;
                                    if(in_array($fieldname, $e->fields))
                                    {
                                        if(is_array($e->fields[$fieldname]))
                                        {
                                            $childattribute = $e->fields[$fieldname];
                                            $childattribute = $childattribute['childattribute'];
                                        }
                                    }
                                    if(is_null($childattribute))
                                    {
                                        $fieldvalue = $field->textContent;
                                        if(array_key_exists($fieldname, $e->fields))
                                        {
                                            $etfield = $e->fields[$fieldname];
                                            if($fieldvalue == '')
                                            {
                                                $fieldvalue2 = 'NULL';
                                            }
                                            else
                                            {
                                                $fieldvalue2 = quote_smart($fieldvalue);
                                            }
                                        }
                                        else
                                        {
                                            $fieldvalue2 = quote_smart($fieldvalue);
                                        }
                                        $fieldsnames[] = "`$fieldname`";
                                        $values[] = $fieldvalue2;
                                        $fieldscollection[] = Array('name'=>$fieldname, 'value'=>$fieldvalue);
                                    }
                                }
                                $fieldsnames2 = implode(',', $fieldsnames);
                                $values2 = implode(',', $values);
                                $tsql[] = "INSERT INTO $entityname($fieldsnames2) VALUES($values2)";
                            }
                        }
                    }
                }
            }
            if(transact_query($tsql))
            {
                $out = ob_get_clean();
                header('Location: '.$_SERVER['SCRIPT_NAME'].'?ok=import');
                exit;
            }
        }
    $import_string = null;
    ?>
    &nbsp;
    <table cellspacing="0" cellpadding="0" border="1">
    <tr><td valign="top">
        <fieldset>
            <legend>Экспорт</legend>
            <form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" style="margin: 0px; ">
            <?php
                $ents = Array();
                foreach($mikron->EntityManager->Items() as $entity_name)
                {
                    if(class_exists($entity_name))
                    {
                        $entity = new $entity_name();
                        $ents[$entity_name] = $entity->description();
                    }
                    else
                    {
                        $ents[$entity_name] = $entity_name;
                    }
                }
            ?>
            <input type="hidden" name="makeexport" value="true">
            <table>
            <tr>
            <td>
                <?php 
                    $ControlName = 'entitiy_names_export_only[]';
                    $t4 = new html_table(4, 'ent_table');
                    foreach($ents as $editor_key => $editor_value)
                    {
                        $t4->newcol();
                        ?><input type="checkbox" name="<?php echo $ControlName; ?>" value="<?php echo $editor_key; ?>">
                         <span title="<?php echo $editor_key; ?>"><a href="entityed.php?entityname=<?php echo $editor_key; ?>"><?php echo $editor_value, '</a></span><br />';
                    }
                    $t4->end();
                    ?>
                </td>
                </tr>
                <tr><td><input type="checkbox" name="export[includelog]"> Вложить логи</td></tr>
                <tr><td><input type="checkbox" name="export[includerecycle]"> Вложить удаленные записи</td></tr>
                <tr><td><input type="submit" value="Экспорт"></td></tr>
            </table>
        </form>
        </fieldset>
    </td>
    </table>
    
    <h2>Файлы экспорта:</h2><?php

    if(isset($_GET['import']))
    {
        $commands = $_SESSION['sql_import_commands'];
        $import_key = $_GET['import'];
        if(array_key_exists($import_key, $commands))
        {
            $command = $commands[$import_key];
            // $command = str_replace('sql', 'tql', $command);
            $code = 0;
            system($command, $code);
            if($code == 0)
            {
                ?><span class="okmessage">Импорт произведен успешно.</span><?php                
            }
            else
            {
                ?><span class="mikroncms_error">При импорте произошла ошибка.</span><?php
            }
        }
    }

    $exports = Array();
    $import_dir = constant('CURRENTSITE_DIR').'/private/backups';
    if(file_exists($import_dir) && is_dir($import_dir))
    {
        $dir = opendir($import_dir);
        while ($d = readdir($dir))
        {
            if(is_file($import_dir.'/'.$d))
            {
                switch($d)
                {
                    case '.': case '..':
                        break;
                    default:
                        $sql_file = realpath($import_dir.'/'.$d);
                        if(substr(strtolower($sql_file), -4, 4) == '.sql')
                        {
                            $xml_file = null;
                            $exports[] = Array('xml' => $xml_file, 'sql' => $sql_file);
                        }
                        break;
                }
            }
        }
    }

    if(count($exports) < 1)
    {
        ?><font>Список пуст.</font><?php
    }
    else
    {
        $domain = $_SERVER['SERVER_NAME'];
        $site = constant('SITE_NAME');
        $bd = constant('bdname');
        $h = constant('host');
        $u = constant('user');
        $p = constant('pass');
        $docroot = realpath(constant('CURRENTSITE_DIR'));
        $t = new html_table(null, 'table3');
        // $t->addhead('XML-файл');
        $t->addhead('SQL-файл');
        $t->addhead('Команда восстановления');
        $t->addhead('Размер');
        foreach($exports as $export)
        {
            $xmlfile = $export['xml'];
            $xmlfile = str_replace('\\', '/', $xmlfile);
            $xmlfile_path = substr($xmlfile, strlen($docroot));
            $xmlfile_title = basename(constant('CURRENTSITE_DIR').'/'.$xmlfile);
            $sqlfile = $export['sql'];
            $sqlfile = str_replace('\\', '/', $sqlfile);
            $sqlfile_path = substr($sqlfile, strlen($docroot));
            $sqlfile_title = 'Скачать';
            $import_string = "mysql -h $h -u $u -p$p $bd < ".$sqlfile;
            $t->newcol("<a href=\"$sqlfile_path\">$sqlfile_title</a>");
            $sql_files = Array();

            if(array_key_exists('sql_import_commands', $_SESSION))
            {
                    $sql_files = $_SESSION['sql_import_commands'];
                    if(!is_array($sql_files))
                    {
                        $sql_files = Array();
                    }
            }
            $sqlfile_key = md5_file($sqlfile);
            $sql_files[$sqlfile_key] = $import_string;
            $_SESSION['sql_import_commands'] = $sql_files;
            
            echo sprintf('&nbsp;<a onclick="return confirm(\'Вы уверены, что хотите выполнить импорт из данного файла?\');" href="export.php?import=%s">Выполнить</a>', $sqlfile_key);
            $t->newcol($import_string);
            $size = round(filesize($sqlfile) / 1024 / 1024, 2);
            if($size == 0)
            {
                $size = round(filesize($sqlfile) / 1024 / 1024, 4);
            }
            $t->newcol($size.' <span class="disabledtext">Мб</span>', true, 'right');
        }
        $t->end();
    }

$mikron->Page->EndBody(); ?>